var ClubTableItemType = {
    Type_CreatRoom: 0,  //创建房间状态
    Type_WaitJoin: 1,   //等待加入状态
    Type_StartRoom: 2,       //游戏中
};
var ClubTableItem = Item.extend({
    _ccsFileName: res.ClubTableItemUnit_json,
    _tableInfos: null,
    //不同玩家人数的座位顺序 key玩家最大人数  value:顺序
    // UI界面头像顺序
    // 0  1
    // 2  3
    _seatOrder: {
        2: [0, 3],
        3: [0, 1, 2],
        4: [0, 1, 2, 3],
        5: [0, 1, 2, 3, 4],
        6: [0, 1, 2, 3, 4, 5],
        9: [0, 1, 2, 3, 4, 5, 6, 7, 8],
    },
    _mapid2color:{
        101: "_c3",
        301: "_c1",
        302: "_c2"
    },

    _tableFor9Offest: 30,
    onEnter: function () {
        Item.prototype.onEnter.call(this);
        TouchUtil.setOnclickListener(this._nodeList['touch0'], this._clickTouch.bind(this), {
            swallowTouches: false,
            isScroll: true
        });
        TouchUtil.setOnclickListener(this._nodeList['touch1'], this._clickTouch.bind(this), {
            swallowTouches: false,
            isScroll: true
        });
        this._initAllListeners();
    },

    /**
     * 初始化牌桌显示状态
     * @private
     */
    _initTable: function () {
        for (var i = 0; i < 2; i++) {
            this._nodeList['table' + i + '.state'].setVisible(false);
            this._nodeList['table' + i + '.lb_num'].setVisible(false);
            this._nodeList['table' + i + '.lb_name'].setVisible(false);
            this._nodeList['table' + i + '.lb_progress'].setVisible(false);
            this._nodeList['table' + i + '.lb_plaeyrs'].setVisible(false);
            this._nodeList['table' + i + '.idx_sp'].setVisible(false);
            for (var j = 0; j < 4; j++) {
                this._nodeList['table' + i + '.row' + j].setVisible(false);
                this._nodeList['table' + i + '.btn_joinTable' + j].setVisible(false);
            }
        }
    },
    _initEventListeners: function () {
        this._eventListeners = {};
        //监听UI 事件
        this._eventListeners[ClubEvent.RefreshOffLineEvent] = '_refeshOffLine';
        this._eventListeners[ClubEvent.RefreshTableEvent] = '_refeshTable';
    },

    _refeshOffLine: function () {
        var tableInfos = this._tableInfos || [];
        for (var i = 0; i < tableInfos.length; i++) {
            var info = tableInfos[i];
            if (info['roomInfo']) {
                this._initSeats(i, info);
            }
        }
    },

    _refeshTable: function (clubId) {
        var tableList = ClubDataManager.getCurrentTableWindowRoomList();
        this.refreshData(clubId, tableList[this._idx], this._currentSelectFloor, this._idx);
    },

    refreshData: function (clubId, tableInfos, currentSelectFloor, idx) {
        this._idx = idx;
        if (parseInt(tableInfos) == 0 || tableInfos == undefined) {
            this.setVisible(false);
            return;
        }
        this.setVisible(true);
        this._clubId = clubId;
        this._tableInfos = tableInfos;
        this._currentSelectFloor = currentSelectFloor;
        this._nodeList['table1'].setVisible(tableInfos.length > 1);
        this._initTable();
        for (var i = 0; i < tableInfos.length; i++) {
            var info = tableInfos[i];
            var tableKey = 'table' + i;

            info.isAllReady = this._checkRoomIsAllReady(info);
            this._refreshTableNode(tableKey, info.maxPlayerNum, info.options.mapid);
            this._nodeList[tableKey + '.lb_name'].setVisible(true);
            this._nodeList[tableKey + '.lb_name'].setString(info.remarks || info.name);

            if (info.table_state == ClubTableItemType.Type_CreatRoom) {
                this._nodeList[tableKey + '.idx_sp'].setVisible(true);
                this._nodeList[tableKey + '.idx_sp'].setTexture(res['club_icon_wanfa' + (5 - info.pos)]);
            } else if (info.table_state == ClubTableItemType.Type_WaitJoin) {
                this._initWaitJoinStyle(i, info);
            } else if (info.table_state == ClubTableItemType.Type_StartRoom) {
                this._initStartRoomStyle(i, info);
            }
        }
    },

    _createChair: function (tableKey, maxPlayerNum) {
        var offsetY = this._tableFor9Offest;
        var chairPosType = {
            5: [cc.p(150, 255 + offsetY)],
            6: [cc.p(70, 255 + offsetY), cc.p(230, 255 + offsetY)],
            9: [
                cc.p(150, 255 + offsetY),
                cc.p(70, 255 + offsetY),
                cc.p(230, 255 + offsetY),
                cc.p(85, 120 + offsetY),
                cc.p(215, 120 + offsetY)
            ],
        };
        var chairPos = chairPosType[maxPlayerNum];
        var posIndex = 0;
        for (var i = 4; i < maxPlayerNum; i++) {
            var chair = this._nodeList[tableKey + '.chair' + i];
            if (!chair || !cc.sys.isObjectValid(chair)) {
                var resPath = i > 6 ? res.club_table_chair_1 : res.club_table_chair_0;
                var chairZ = i > 6 ? 99 : -1;
                chair = new cc.Sprite(resPath);
                this._nodeList[tableKey].addChild(chair, chairZ);
                this._nodeList[tableKey + '.chair' + i] = chair;
            }
            chair.setVisible(true);
            chair.setPosition(chairPos[posIndex]);
            posIndex++;
        }
    },

    _createHead: function (tableKey, maxPlayerNum) {
        var offsetY = this._tableFor9Offest;
        var headPosType = {
            5: [
                cc.p(-20, 285 + offsetY),
                cc.p(-20, 170 + offsetY),
                cc.p(310, 285 + offsetY),
                cc.p(310, 170 + offsetY),
                cc.p(143, 325 + offsetY),
            ],
            6: [
                cc.p(-20, 285 + offsetY),
                cc.p(-20, 170 + offsetY),
                cc.p(310, 285 + offsetY),
                cc.p(310, 170 + offsetY),
                cc.p(63, 325 + offsetY),
                cc.p(223, 325 + offsetY)
            ],
            9: [
                cc.p(-20, 285 + offsetY),
                cc.p(-20, 170 + offsetY),
                cc.p(310, 285 + offsetY),
                cc.p(310, 170 + offsetY),
                cc.p(143, 325 + offsetY),
                cc.p(63, 325 + offsetY),
                cc.p(223, 325 + offsetY),
                cc.p(85, 170 + offsetY),
                cc.p(215, 170 + offsetY)
            ],
        };
        var headPos = headPosType[maxPlayerNum];
        for (var i = 0; i < maxPlayerNum; i++) {
            var head = this._nodeList[tableKey + '.row' + i];
            if (!head || !cc.sys.isObjectValid(head)) {
                head = duplicateNode(this._nodeList[tableKey + '.row0']);
                this._nodeList[tableKey].addChild(head, 100);
                this._nodeList[tableKey + '.row' + i] = head;
            }
            head.setVisible(false);
            head.setPosition(headPos[i]);
        }
    },

    _createJoinLabel: function (tableKey, maxPlayerNum) {
        var offsetY = this._tableFor9Offest;
        var joinPosType = {
            5: [
                cc.p(-20, 285 + offsetY),
                cc.p(-20, 170 + offsetY),
                cc.p(310, 285 + offsetY),
                cc.p(310, 170 + offsetY),
                cc.p(152, 325 + offsetY)
            ],
            6: [
                cc.p(-20, 285 + offsetY),
                cc.p(-20, 170 + offsetY),
                cc.p(310, 285 + offsetY),
                cc.p(310, 170 + offsetY),
                cc.p(72, 325 + offsetY),
                cc.p(232, 325 + offsetY)],
            9: [
                cc.p(-20, 285 + offsetY),
                cc.p(-20, 170 + offsetY),
                cc.p(310, 285 + offsetY),
                cc.p(310, 170 + offsetY),
                cc.p(152, 325 + offsetY),
                cc.p(72, 325 + offsetY),
                cc.p(232, 325 + offsetY),
                cc.p(85, 170 + offsetY),
                cc.p(215, 170 + offsetY)
            ],
        };
        var joinPos = joinPosType[maxPlayerNum];
        for (var i = 0; i < maxPlayerNum; i++) {
            var joinLabel = this._nodeList[tableKey + '.btn_joinTable' + i];
            if (!joinLabel || !cc.sys.isObjectValid(joinLabel)) {
                joinLabel = duplicateNode(this._nodeList[tableKey + '.btn_joinTable0']);
                this._nodeList[tableKey].addChild(joinLabel, 100);
                this._nodeList[tableKey + '.btn_joinTable' + i] = joinLabel;
            }
            joinLabel.setVisible(false);
            joinLabel.setPosition(joinPos[i]);
        }
    },

    /**
     * 隐藏指定桌子的 头像 椅子 加入文字 节点
     * @param tableKey
     * @private
     */
    _hideTableNode: function (tableKey) {
        for (var i = 0; i < 9; i++) {
            var joinLabel = this._nodeList[tableKey + '.btn_joinTable' + i];
            var head = this._nodeList[tableKey + '.row' + i];
            var chair = this._nodeList[tableKey + '.chair' + i];
            if (joinLabel && cc.sys.isObjectValid(joinLabel)) {
                joinLabel.setVisible(false);
            }
            if (head && cc.sys.isObjectValid(head)) {
                head.setVisible(false);
            }
            if (chair && cc.sys.isObjectValid(chair)) {
                chair.setVisible(false);
            }
        }
    },

    /**
     * 重置牌桌节点坐标
     * @param tableKey
     * @private
     */
    _resetTableNodePos: function (tableKey) {
        var joinLabelPos = [
            cc.p(43, 320),
            cc.p(254, 320),
            cc.p(43, 207),
            cc.p(254, 207),
        ];
        var headPos = [
            cc.p(41, 322),
            cc.p(251, 322),
            cc.p(41, 212),
            cc.p(251, 212),
        ];

        for (var i = 0; i < 4; i++) {
            var joinLabel = this._nodeList[tableKey + '.btn_joinTable' + i];
            var head = this._nodeList[tableKey + '.row' + i];
            if (joinLabel && cc.sys.isObjectValid(joinLabel)) {
                joinLabel.setPosition(joinLabelPos[i]);
            }
            if (head && cc.sys.isObjectValid(head)) {
                head.setPosition(headPos[i]);
            }
        }
    },

    /**
     * 刷新牌桌椅子
     * @param tableKey
     * @param maxPlayerNum
     * @param mapid
     * @private
     */
    _refreshTableNode: function (tableKey, maxPlayerNum, mapid) {
        this._hideTableNode(tableKey);

        if (maxPlayerNum > 4) {
            this._createChair(tableKey, maxPlayerNum);
            this._createHead(tableKey, maxPlayerNum);
            this._createJoinLabel(tableKey, maxPlayerNum);
            this._nodeList[tableKey + '.table'].setTexture(res['club_table_for9']);
            this._nodeList[tableKey + '.table'].y = 180 + this._tableFor9Offest;
            this._nodeList[tableKey + '.lb_name'].y = 255 + this._tableFor9Offest;
            this._nodeList[tableKey + '.lb_progress'].y = 257;
            this._nodeList[tableKey + '.lb_plaeyrs'].y = 257;
        } else {
            this._nodeList[tableKey + '.table'].setTexture(
                res['club_table_for' + maxPlayerNum + (this._mapid2color[mapid] ? this._mapid2color[mapid] : '_c2')]);
            this._nodeList[tableKey + '.table'].y = 180;
            this._nodeList[tableKey + '.lb_name'].y = 250;
            this._nodeList[tableKey + '.lb_name'].x = 138;
            this._nodeList[tableKey + '.lb_progress'].y = 225;
            this._nodeList[tableKey + '.lb_plaeyrs'].y = 225;
            this._resetTableNodePos(tableKey);
        }
    },


    /**
     * 初始化 等待加入 样式
     * @private
     */
    _initWaitJoinStyle: function (tableIndex, info) {
        var tableKey = 'table' + tableIndex;
        this._nodeList[tableKey + '.lb_plaeyrs'].setVisible(true);
        this._nodeList[tableKey + '.idx_sp'].setVisible(false);
        this._nodeList[tableKey + '.lb_plaeyrs'].x = 138;
        this._nodeList[tableKey + '.lb_plaeyrs'].setString(info.currentPlayerNum + '/' + info.maxPlayerNum + '人');
        this._nodeList[tableKey + '.lb_num'].setVisible(false);

        if ((info.currentPlayerNum == info.maxPlayerNum) && !info.isAllReady) {
            this._nodeList[tableKey + '.lb_plaeyrs'].setString('人满未开局');
        }

        // this._nodeList[tableKey + '.lb_num'].setString('房号:' + info.roomInfo.room_id);
        this._initSeats(tableIndex, info);
    },

    /**
     * 初始化 已经开局 样式
     * @param tableIndex
     * @param info
     * @private
     */
    _initStartRoomStyle: function (tableIndex, info) {
        var tableKey = 'table' + tableIndex;
        this._nodeList[tableKey + '.lb_progress'].setVisible(true);
        this._nodeList[tableKey + '.lb_progress'].x = 138;
        this._nodeList[tableKey + '.idx_sp'].setVisible(false);
        this._nodeList[tableKey + '.lb_num'].setVisible(false);
        // this._nodeList[tableKey + '.lb_num'].setString('房间号:' + info.roomInfo.room_id);

        var option = null;
        try {
            option = JSON.parse(info.roomInfo.option);
        } catch (e) {
            option = info.roomInfo.option;
        }

        var used = info.roomInfo.used || 0;
        var current_rounds = option.mapid >= 300 ? (!used ? 1 : (used + 1)) : used;
        var total_round = (option.rounds || option.jushu);
        var str = current_rounds + '/' + total_round;
        this._nodeList[tableKey + '.lb_progress'].setString(str + '局');
        this._initSeats(tableIndex, info);
    },

    /**
     * 刷新玩家状态
     * @param rowKey
     * @param info
     * @param playerIndex
     * @private
     */
    _refreshHeadState: function (rowKey, info, playerIndex) {
        var uid = info.roomInfo['uids'][playerIndex];
        var label_offLine = this._nodeList[rowKey].getChildByName('label_offLine');
        var label_ready = this._nodeList[rowKey].getChildByName('label_ready');
        var bg_offLine = this._nodeList[rowKey].getChildByName('bg_offLine');
        var lb_offLine = this._nodeList[rowKey].getChildByName('lb_offLine');

        label_offLine.setVisible(false);
        label_ready.setVisible(false);
        bg_offLine.setVisible(false);
        lb_offLine.setVisible(false);

        // 如果房间玩家没有全部准备的时候 需要显示每个玩家的装状态
        /*
        if (!info.isAllReady && info.roomInfo['user_stats'] && info.roomInfo['user_stats'][playerIndex] == 1) {
            label_ready.setVisible(true);
        }
         */
        var memberInfo = ClubDataManager.getClubSingleMemberInfo(this._clubId, uid);
        if (memberInfo && memberInfo.state == ClubDataManager.MemberState_OffLine) {
            label_ready.setVisible(false);
            //label_offLine.setVisible(true);
            //bg_offLine.setVisible(true);
            //lb_offLine.setVisible(true);
            //lb_offLine.setString(memberInfo.offLineTimerStr || '<1分钟');
        }
    },


    /**
     * 初始化 座椅
     * @param tableIndex
     * @param info
     * @private
     */
    _initSeats: function (tableIndex, info) {
        var tableKey = 'table' + tableIndex;
        var _seats = this._seatOrder[info.maxPlayerNum];
        for (var j = 0; j < _seats.length; j++) {
            var rowKey = tableKey + '.row' + _seats[j];
            var joinLabel = this._nodeList[tableKey + '.btn_joinTable' + _seats[j]];
            var head = info.roomInfo['heads'][j] || res.defaultHead;
            var nicknames = info.roomInfo['nicknames'][j] || info.roomInfo['uids'][j];
            if (info.roomInfo['uids'][j] && this._nodeList[rowKey]) {
                this._nodeList[rowKey].setVisible(true);
                joinLabel.setVisible(false);

                loadImageToSprite(head, this._nodeList[rowKey].getChildByName('head'));
                this._nodeList[rowKey].getChildByName('lb_name').setString(ellipsisStr(nicknames, ClubDataManager.NirckNameSize));
                this._refreshHeadState(rowKey, info, j);
            } else {
                this._nodeList[rowKey].setVisible(false);
                joinLabel.setVisible(true);
            }
        }
    },


    _clickTouch: function (target) {
        var str = target.getName();
        var index = str.charAt(str.length - 1);
        var table = this._tableInfos[index];
        if (table) {
            if (table.table_state == ClubTableItemType.Type_CreatRoom) {
                this._tableTouchType_CreatRoom(table, index);
            } else if (table.table_state == ClubTableItemType.Type_WaitJoin) {
                this._tableTouchType_WaitJoin(table, index);
            } else if (table.table_state == ClubTableItemType.Type_StartRoom) {
                this._showRoomInfo(index);
            }
        }
    },
    _tableTouchType_CreatRoom: function (table, index) {
        if (ClubDataManager.getUidIsBackList(this._clubId, gameData.uid)) {
            showAlert('你已被管理员禁玩,请联系管理员~');
            return;
        }
        //如果是桌内通过小助手返回俱乐部 点击牌桌
        if (ClubDataManager.getClubTableWindowState()) {
            this._alreadyInRoom(undefined, index);
            return;
        }
        this._createRoom(table);
    },

    _createRoom: function (table) {
        clubMsgManager.requestCreateRoom(table);
    },

    _joinRoom: function (table) {
        clubMsgManager.requestJoinRoom(table.roomInfo.room_id);
    },

    _tableTouchType_WaitJoin: function (table, index) {
        if (ClubDataManager.getUidIsBackList(this._clubId, gameData.uid)) {
            showAlert('你已被管理员禁玩,请联系管理员~');
            return;
        }
        //如果是桌内通过小助手返回俱乐部 点击牌桌
        if (ClubDataManager.getClubTableWindowState()) {
            this._alreadyInRoom(table.roomInfo.room_id, index);
            return;
        }

        //显示牌桌信息 只有群主可以管理员才可以显示
        if (this._showRoomInfo(index, table)) {
            return;
        }

        //如果是混合楼层 则弹出玩法介绍
        if (this._currentSelectFloor == 0) {
            showWindow('ClubJoinRoomTipsWindow', table, this._joinRoom.bind(this, table));
            return;
        }
        //加入房间
        this._joinRoom(table);
    },


    /**
     * 已经在房间
     * @private
     */
    _alreadyInRoom: function (roomId, index) {
        //暂时屏蔽该组件
        return;
        if (roomId && roomId == gameData.roomId) {
            if (!this._returnRoomUnit) {
                this._returnRoomUnit = addUnit('ClubReturnRoomUnit', this._nodeList['table' + index + '.returnRoomUnit'], this._tableInfos[index]);
            } else {
                this._returnRoomUnit.setVisible(true);
            }
        } else {
            clubMsgManager.requestQuitRoom('是否退出当前房间, 加入其他房间？');
        }
    },

    _showRoomInfo: function (index, table) {
        //if (ClubDataManager.isSelfAdministration(this._clubId, gameData.uid)) {
            showWindow('ClubTableInfoWindow', this._tableInfos[index], this._clubId,
                ClubDataManager.isSelfAdministration(this._clubId, gameData.uid), table);
            return true;
        //}
        //return false;
    },


    /**
     * 检测房间是否全部准备
     * @param info
     * @returns {boolean}
     * @private
     */
    _checkRoomIsAllReady: function (info) {
        var isAllReady = true;
        if (info.roomInfo && info.roomInfo['user_stats']) {
            var userStats = info.roomInfo['user_stats'] || [];
            for (var j = 0; j < info.maxPlayerNum; j++) {
                if (userStats[j] != 1) {
                    isAllReady = false;
                }
            }
        }
        return isAllReady;
    },


    onExit: function () {
        this._super();
        this.setVisible(false);
    },


});